/*
 * Copyright 2011 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.code.qsecurity.client;

import com.google.code.qsecurity.client.event.LoginFormEvent;
import com.google.code.qsecurity.client.event.OfflineEvent;
import com.google.code.qsecurity.client.event.OnlineEvent;
import com.google.code.qsecurity.client.event.StateChangeHandler;
import com.google.code.qsecurity.client.mvp.SecurityActivityManager;
import com.google.code.qsecurity.client.mvp.SecurityActivityMapper;
import com.google.code.qsecurity.client.mvp.StateController;
import com.google.code.qsecurity.client.util.CookieUtil;
import com.google.code.qsecurity.shared.QSettings;
import com.google.code.qsecurity.shared.proxy.UserProxy;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.inject.Inject;

public class QLibrary {
	
	private final EventBus eventBus;
	private final StateController stateController;
	private SecurityActivityManager activityManager;
	private QSettings settings;
	
	@Inject
	public QLibrary(QClientFactory clientFactory, EventBus eventBus,
			StateController stateController, SecurityActivityMapper activityMapper,
			SecurityActivityManager activityManager) {
		this.eventBus = eventBus;
		this.stateController = stateController;
		this.activityManager = activityManager;
		this.settings = new QSettings();
	}
	
	void handleLoginRequest() {
		eventBus.fireEvent(new LoginFormEvent(""));
	}

	void handleLogout(UserProxy user) {
		eventBus.fireEvent(new OfflineEvent(user));
	}

	void updateUserEmail(UserProxy user, String newEmail) {
		// TODO
		//eventBus.fireEvent(new EmailUpdateEvent(user, newEmail));
	}

	HandlerRegistration addLoginHandler(StateChangeHandler handler) {
		return eventBus.addHandler(OnlineEvent.getType(), handler);
	}

	UserProxy getOnlineUser() {
		// TODO
		return stateController.getUser();
	}

	void init(String appName, String adminAddress) {
		// setDisplay() must be called even if the given widget is not attached or used
		activityManager.setDisplay(new SimplePanel());
		
		CookieUtil.init();
		
		settings.setAppName(appName);
		settings.setAdminAddress(adminAddress);
	}

	String getAppName() {
		return settings.getAppName();
	}

	String getAdminAddress() {
		return settings.getAdminAddress();
	}
	
}
